<script setup lang='ts'>
import type { IProps } from '@/components/fl-upload-progress.vue'

import breadCrumb from '@/components/bread-crumb.vue'
import FlUploadProgress from '@/components/fl-upload-progress.vue'
import { FlowCatchOption } from '@/constants'
import { ToMember } from '@/helper'
import { acceptApplication, useGetAnnouncementDetail } from '@fl/api/bidding-api'
import { useCanBidding } from '@fl/api/man-api/message-center'
import { SubmitBtn } from '@fl/components'
import { useUserStore } from '@fl/store/modules/user'
import { downloadFileWithUrl } from '@fl/utils/fn'
import dayjs from 'dayjs'
import { cloneDeep } from 'lodash-es'

import Footer from '../footer/footer.vue'
import Introduce from './components/introduce.vue'

import tenderBg from '/assets/home/tender-bg.png'

const { query } = useRoute()
const { push } = useRouter()

const { announcementId, biddingId } = query
const announcementIds = ref(announcementId?.toString() || '')
const biddingIds = ref(biddingId?.toString() || '')
const { data } = useGetAnnouncementDetail(announcementIds)

const tenderData = computed(() => {
    return data.value
})

const userStore = useUserStore()
const userIsLogin = computed(() => {
    return Boolean(userStore.userInfo)
})
const isApply = computed(() => {
    return dayjs().isBefore(dayjs(tenderData.value.applicationEndTime))
})
// 是否需要显示报名按钮
const applyStatus = computed(() => {
    return tenderData.value.announcementType === '1' && tenderData.value.procureType === 2
})
// 是否需要显示异常按钮
const isCatchStatus = computed(() => {
    return tenderData.value.abnormalProcess !== null
})
const catchStatus = computed(() => {
    const aStatus = FlowCatchOption[tenderData.value.abnormalProcess]
    return aStatus ? (`已${aStatus}`) : '异常状态'
})
const fileList = computed(() => {
    if (tenderData.value.fileJson && tenderData.value.fileJson !== '') {
        return JSON.parse(tenderData.value.fileJson)
    }
    return []
})

const applyName = computed(() => {
    if (!tenderData.value) {
        return '公告'
    }
    if (tenderData.value.announcementType === '1') {
        return '招标公告'
    }
    else if (tenderData.value.announcementType === '2') {
        return '中标公告'
    }
    else if (['4', '5', '6', '7'].includes(tenderData.value.announcementType)) {
        return '变更公告'
    }
    else {
        return '其他公告'
    }
})

const form = ref({ data: '' })
const config: IProps = {
    accept: '.pdf,.doc,.docx,.xlsx', // pdf、doc、docx、xlsx
    disabled: false,
    drag: false,
    fileSize: 200, // MB
    hidePlusIcon: false,
    isCheckWidthOrHeight: false,
    isPrivate: false,
    isVideo: false,
    limit: 10,
    listType: 'text',
    showRemoveIcon: true,
    splitSymbol: ',',
    tips: false,
}
const tenderFile = ref<fileUpload[]>([])

// const isGys = computed(() => {
//     return ((userStore!.userInfo || {}) as any).userTypeCategory === '供应商'
// })

const canNotBiddingReason = ref('')

// const isMember = computed(() => canBiddingData.value?.isMember === 1)

function showOpenMemberModel() {
    memberDialogVisible.value = true
}

function toApply() {
    if (!userIsLogin.value) {
        ElMessage({ message: '请登录后报名', type: 'error' })
        return false
    }

    try {
        getCanBidding().then((res) => {
            if (!res) {
                return showOpenMemberModel()
            }
            centerDialogVisible.value = true
        })
    }
    catch (e) {
        console.log(e)
    }
}

function getCanBidding() {
    return new Promise((resolve, reject) => {
        useCanBidding().then((res) => {
            canNotBiddingReason.value = res?.canNotBiddingReason
            resolve(res?.canBidding)
        }).catch((err) => {
            reject(err)
        })
    })
}

const isTenderLoading = ref(false)
async function tenderHandle() {
    if (!(tenderData.value.openViewFlag && isApply.value)) {
        return
    }
    if (!isApply.value)
        return

    if (uploadFile.value && uploadFile.value.hasUploading) {
        ElMessage.warning('请耐心等待上传完成')
        return
    }
    const acceptData = {
        biddingId: biddingIds.value,
        tenderFiles: tenderFile.value.filter(item => form.value.data.includes(item.fileUrl)),
    }
    isTenderLoading.value = true
    try {
        const res = await acceptApplication(acceptData)
        if (res.code === 200) {
            ElMessage({ message: '提交成功', type: 'success' })
            push('/')
        }
        else {
            ElMessage({ message: res.msg, type: 'error' })
        }
    }
    catch (e) {
        isTenderLoading.value = false
    }
    finally {
        isTenderLoading.value = false
    }
}

const uploadFile = ref()

type fileUpload = {
    fileBizType: number
    fileBizTypeName: string
    fileName: any
    fileSize: any
    fileSuffix: any
    fileUrl: any
    id?: string
}

function uploadSuc(fileInfo) {
    console.log(fileInfo)
    const data = cloneDeep(fileInfo)
    const names = data.name.split('.')
    const files: fileUpload = {
        fileBizType: 5,
        fileBizTypeName: '报名附件',
        // fileId: 0,
        fileName: data.name,
        fileSize: data.file.size,
        fileSuffix: names[names.length - 1],
        fileUrl: data.url,
    // id: biddingIds.value,
    }
    tenderFile.value.push(files)
}

function removeCall(data) {
    console.log(data)
}

const centerDialogVisible = ref(false)
const memberDialogVisible = ref(false)
</script>

<template>
    <div class="h-221">
        <el-image class="h-[100%] w-[100%]"
                  :src="tenderBg"
        />
    </div>

    <div class="pl-[10%] pr-[10%]">
        <breadCrumb class="mt-10"
                    :crumb-list="[{ name: 'root-apply', title: applyName }]"
        />

        <ElCard v-if="tenderData"
                class="pl-20 pr-20"
                shadow="never"
        >
            <div class="tenderApplication">
                <div class="flex flex-row">
                    <h1 class="title">
                        {{ tenderData.title }}
                    </h1>

                    <p v-if="applyStatus"
                       class="status"
                    >
                        <el-tag v-if="isCatchStatus"
                                type="warning"
                        >
                            {{ catchStatus }}
                        </el-tag>

                        <el-tag v-else-if="isApply"
                                type="success"
                        >
                            正在报名
                        </el-tag>

                        <el-tag v-else
                                type="warning"
                        >
                            报名结束
                        </el-tag>
                    </p>
                </div>

                <div class="detail mr-30 mt-20">
                    <span>发布时间：{{ tenderData.publishedTime }}</span>

                    <span class="ml-30">所属公司：{{ tenderData.company }}</span>
                </div>

                <el-divider />

                <div v-if="applyStatus"
                     class="mb-20"
                >
                    <p class="footer">
                        <span class="mr-30">报名截止时间：{{ tenderData.applicationEndTime }}</span>

                        <el-button v-if="isCatchStatus"
                                   type="info"
                        >
                            {{ catchStatus }}
                        </el-button>

                        <el-button v-else-if="tenderData.openViewFlag && isApply"
                                   type="primary"
                                   @click="toApply"
                        >
                            报名
                        </el-button>

                        <el-button v-else-if="!tenderData.openViewFlag"
                                   type="info"
                        >
                            已报名
                        </el-button>

                        <el-button v-else-if="!isApply"
                                   type="info"
                        >
                            报名结束
                        </el-button>
                    </p>
                </div>

                <div class="w-e-text-container"
                     style="min-height: 500px;"
                >
                    <div data-slate-editor
                         v-html="tenderData.announcementInfo"
                    />
                </div>

                <div v-if="fileList.length > 0">
                    供应商报名文件下载
                </div>

                <div>
                    <p v-for="(item) in fileList"
                       :key="item.fileName"
                    >
                        <el-link @click="downloadFileWithUrl(item.fileUrl, item.fileName)">
                            {{ item.fileName }}
                        </el-link>
                    </p>
                </div>
            </div>
        </ElCard>

        <el-dialog v-model="centerDialogVisible"
                   title="报名附件"
                   width="500"
                   center
        >
            <span class="mb-10 inline-block">
                支持上传pdf、doc、docx、xlsx格式文件，上传最大限制10个附件，单个文件限制200M
            </span>

            <FlUploadProgress v-if="applyStatus && isApply && tenderData.openViewFlag"
                              v-bind="config"
                              ref="uploadFile"
                              v-model="form.data"
                              @success="uploadSuc"
                              @remove="removeCall"
            />

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">
                        取消
                    </el-button>

                    <SubmitBtn type="primary"
                               :disabled="isTenderLoading"
                               :loading="isTenderLoading"
                               @click="tenderHandle"
                    >
                        报名
                    </SubmitBtn>
                </div>
            </template>
        </el-dialog>

        <el-dialog v-model="memberDialogVisible"
                   :title="canNotBiddingReason"
                   width="70%"
                   center
        >
            <Introduce />

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="memberDialogVisible = false">
                        取消
                    </el-button>

                    <el-button type="primary"
                               @click="ToMember"
                    >
                        去开通
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>

    <Footer />
</template>

<style lang="scss">
.w-e-text-container [data-slate-editor] table tr {
    height: 27.91px;
}

.tenderApplication {
    padding: 20px;

    .status,
    .title {
        text-align: center;
        font-weight: bold;
        font-size: 30px;
        margin-right: 10px;
    }

    .detail {
        display: flex;
        justify-content: flex-start;
    }

    .footer {
        text-align: right;
    }
}
</style>
